#!/usr/bin/env python
import commands, time, re
import os

def drop_caches():
    number_re = " +([0-9]+\.[0-9]+|[0-9]+)"
    before = commands.getoutput('cat /proc/meminfo')
    mem_total = re.findall("MemTotal:"+number_re, before)[0]
    before_cached = re.findall("Cached:"+number_re, before)[0]
    before_free = re.findall("MemFree:"+number_re, before)[0]
    commands.getoutput('echo 3 | sudo tee /proc/sys/vm/drop_caches')
    after = commands.getoutput('cat /proc/meminfo')
    after_cached = re.findall("Cached:"+number_re, after)[0]
    after_free = re.findall("MemFree:"+number_re, after)[0]
    print 'drop caches.'
    print 'MemTotal:', mem_total,'kB'
    print 'before MemFree:', before_free,'kB','before Cached:', before_cached,'kB'
    print 'after MemFree:', after_free,'kB','after Cached:', after_cached,'kB'

for version in ['CCoarseGrainedLockStack','CLockFreeStack','CEliminationBackoffStack']:
    for participants in ['4','8','12','16','20','24','28','32']:
        for pushRatio in ['0.25','0.5','0.75','1']:
            for operations in ['1000','10000','100000','1000000']:
                for intervals in ['0']:
                    for capacity in [str(int(participants)/4)]: # for CEliminationBackoffStack
                        for timeout in ['5000']: # for CEliminationBackoffStack
                            cmd = './test_stack '+participants+' '+pushRatio+' '+operations+' '+intervals+' '+capacity+' '+timeout
                            output = commands.getoutput(cmd)
                            print output

                            fname = version+'.'+participants+'-'+pushRatio+'-'+operations+'-'+intervals+'.log'
                            f = open('./log/'+fname,'w+')
                            f.write(cmd)
                            f.write(output)
                            f.write('\n')
                            f.close()

                            drop_caches()

